<?php

namespace app\api\controller\xiluhouse;

use app\common\controller\Api;
use app\common\model\xiluhouse\User;
use think\Db;

/**
 * @title   积分类（新增）
 * @desc    获取每日任务、签到等的接口
 */
class Score extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @title  每日签到页面数据
     * @desc  获取-每日签到页面数据
     *
     * @return int   $my_score  0    可用积分
     * @return string   $rule  -    规则
     * @return bool   $today_is_sign  -    今日是否已签到
     * @return array   $sign_data  -        签到数据
     * @return array   $task_data  -        任务数据
     */
    public function index()
    {
        // 获取可用积分
        $data['my_score'] = $this->auth->score;
        // 获取规则
        $data['rule'] = \app\common\model\xiluhouse\Config::getdatas('sign_task_rule');
        // 今天是否已签到
        $model = new \app\common\model\xiluhouse\SignLog;
        $today_sign_exist = $model->where('user_id', $this->auth->id)->whereTime('createtime', 'today')->find();
        $data['today_is_sign'] = $today_sign_exist ? true : false;
        // 获取签到数据
        $init_sign_score = \app\common\model\xiluhouse\Config::getdatas('init_sign_score');
        $add_sign_score = \app\common\model\xiluhouse\Config::getdatas('add_sign_score');
        $sign_data = [];
        if ($today_sign_exist) {
            $sign_week_day = $today_sign_exist['sign_week_day'];
        } else {
            $exist = $model->where('user_id', $this->auth->id)->whereTime('createtime', 'yesterday')->find();
            $sign_week_day = 0;
            if ($exist) {
                $sign_week_day = $exist['sign_week_day'];
            }
        }
        $tmp_arr = ['一', '二', '三', '四', '五', '六', '七'];
        for ($i = 1; $i < 8; $i++) {
            $sign_data[] = [
                'day' => $i,
                'day_text' => '第' . $tmp_arr[$i - 1] . '天',
                'score' => $init_sign_score + ($add_sign_score * ($i - 1)),
                'is_sign' => ($sign_week_day < $i) ? false : true,
            ];
        }
        $data['sign_data'] = $sign_data;
        // 获取任务数据
        $task_model = new \app\common\model\xiluhouse\Task;
        $task_data = $task_model->where('status', 'normal')->order(['weigh' => 'desc'])->select();
        $task_log_model = new \app\common\model\xiluhouse\TaskLog;
        $task_log_data = $task_log_model->where('user_id', $this->auth->id)->whereTime('createtime', 'today')->select();
        foreach ($task_data as $key => &$value) {
            $value->append(['task_log_count', 'is_complete']);
            $value['task_log_count'] = 0;
            foreach ($task_log_data as $k => $v) {
                if ($v['task_id'] == $value['id']) {
                    $value['task_log_count'] = $value['task_log_count'] + 1;
                }
            }
        }
        foreach ($task_data as $key => &$value) {
            $value['is_complete'] = ($value['task_log_count'] >= $value['limit_num']) ? true : false;
        }
        $data['task_data'] = $task_data;
        $this->success('', $data);
    }

    /**
     * @title  立即签到
     * @desc  立即签到
     *
     */
    public function sign()
    {
        // 今天是否已签到
        $model = new \app\common\model\xiluhouse\SignLog;
        $today_sign_exist = $model->where('user_id', $this->auth->id)->whereTime('createtime', 'today')->find();
        if ($today_sign_exist) {
            $this->error('今日已签到');
        }
        $init_sign_score = \app\common\model\xiluhouse\Config::getdatas('init_sign_score');
        $add_sign_score = \app\common\model\xiluhouse\Config::getdatas('add_sign_score');
        $per_sign_day = \app\common\model\xiluhouse\Config::getdatas('per_sign_day');
        $extra_score_rp = \app\common\model\xiluhouse\Config::getdatas('extra_score_rp');
        $exist = $model->where('user_id', $this->auth->id)->whereTime('createtime', 'yesterday')->find();
        $sign_day = 0;
        $sign_week_day = 0;
        if ($exist) {
            $sign_week_day = $exist['sign_week_day'];
            $sign_day = $exist['sign_day'];
        }
        $saveData['score'] = $init_sign_score + ($add_sign_score * $sign_week_day);
        $saveData['user_id'] = $this->auth->id;
        $saveData['sign_day'] = $sign_day + 1;
        $saveData['sign_week_day'] = $sign_week_day + 1;
        $saveData['extra_score'] = 0;
        // 获取额外积分
        if ($saveData['sign_week_day'] % $per_sign_day == 0) {
            // 概率获取数据
            $saveData['extra_score'] = draw_prize($extra_score_rp);
        }
        // 启动事务
        Db::startTrans();
        // 添加签到数据
        $res = $model->save($saveData);
        if (!$res) {
            goto err;
        }
        // 添加积分记录
        User::score($saveData['score'], $this->auth->id, '签到获得积分');
        if ($saveData['extra_score']) {
            User::score($saveData['extra_score'], $this->auth->id, '签到获得额外积分');
        }
        Db::commit();
        $this->success('签到成功');
        err:
        Db::rollback();
        $this->error('签到失败');
    }

    /**
     * @title  做任务
     * @desc  做任务
     * @param int    $task_id  0            任务id
     */
    public function dotask()
    {
        $task_id = $this->request->param('task_id/d', 0);
        if (!$task_id) {
            $this->error('参数错误');
        }
        $task_model = new \app\common\model\xiluhouse\Task;
        $task_info = $task_model->where('status', 'normal')->find($task_id);
        if (!$task_info) {
            $this->error('参数错误');
        }
        $task_log_model = new \app\common\model\xiluhouse\TaskLog;
        $task_log_data = $task_log_model->where('user_id', $this->auth->id)->where('task_id', $task_id)->whereTime('createtime', 'today')->select();
        if ($task_log_data && count($task_log_data) >= $task_info['limit_num']) {
            // $this->error('该任务今日已达到上限');
            $this->success();
        }
        // 启动事务
        Db::startTrans();
        $saveData['user_id'] = $this->auth->id;
        $saveData['task_id'] = $task_id;
        $saveData['score'] = $task_info['score'];
        $res = $task_log_model->save($saveData);
        if (!$res) {
            goto err;
        }
        // 添加积分记录
        User::score($saveData['score'], $this->auth->id, '任务：' . $task_info['name']);
        Db::commit();
        $this->success('提交成功');
        err:
        Db::rollback();
        $this->error('提交失败');
    }

    /**
     * @title  积分明细
     * @desc  获取我的积分明细列表
     *
     */
    public function score_list()
    {
        $model = new \app\common\model\xiluhouse\ScoreLog;
        $list = $model->where('user_id', $this->auth->id)->order(['id' => 'desc'])->paginate();
        $this->success('', $list);
    }
}
